package com.webull.information.center.mam;

import java.beans.PropertyVetoException;
import java.util.Date;
import java.util.List;
import java.util.Optional;

import javax.sql.DataSource;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jsoup.Connection;
import org.jsoup.HttpStatusException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import com.fasterxml.jackson.databind.JsonNode;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.webull.framework.util.UtilJson;
import com.webull.information.center.carwler.common.util.NewsTaskUtil;
import com.webull.securities.client.model.Exchange;

public class GoogleMissss2 {
	protected final Logger logger = LogManager.getLogger(getClass());
	private static final RowMapper<ExchangeGG> exchangeRM = BeanPropertyRowMapper.newInstance(ExchangeGG.class);
	private static final RowMapper<ZzYgTickerMiss> zzYgTickerMissRM = BeanPropertyRowMapper
			.newInstance(ZzYgTickerMiss.class);

	public static void main(String[] args) throws PropertyVetoException {
		GoogleMissss2 miss = new GoogleMissss2();
		miss.processGG(0, 100000);

	}


	public void processGG(int lastId, int max) {

		ThreadPoolTaskExecutor ttt = new ThreadPoolTaskExecutor();
		ttt.setMaxPoolSize(40);
		ttt.initialize();

		do {
			List<ZzYgTickerMiss> query = query(lastId, max);
			if (query == null || query.isEmpty())
				break;

			lastId = query.get(query.size() - 1).getId();

			NewsTaskUtil.multiThreadProcess(query, this::processGgggg, ttt);

			System.out.println("currentdate--->" + new Date() + ";lastId ---->" + lastId);
		} while (true);

		ttt.destroy();
	}



	private static String[] ggDomains = new String[] { "http://www.google.com.hk", "https://www.google.com",
			"http://www.google.co.jp", "http://www.google.co.uk"/* , "http://www.google.cn" */ };
	private static final String STOCKS_QUOTES_PARAM = "http://www.google.com/finance/info?infotype=infoquoteall&q=";
	private void processGgggg(ZzYgTickerMiss miss) {
		// cha google
		// String path = "/finance?q={ex}:{sb}&ei=" +
		// RandomStringUtils.randomAlphanumeric(23) + "&gl=cn";
		String ex = genExchangeCode(miss.getExchangeCode());
		// path = StringUtils.replace(path, "{ex}", ex);
		// path = StringUtils.replace(path, "{sb}", miss.getSymbol());
		String url = STOCKS_QUOTES_PARAM + ex + ":" + miss.getSymbol();
		// if (!StringUtils.equalsIgnoreCase(ex, miss.getExchangeCode()))
		// System.out.println("ex22222222------->" + miss.getExchangeCode() + "-------"
		// + ex);
		// System.out.println("url------->" + url);


		try {
			Connection connection = Jsoup.connect(url);
			connection.ignoreContentType(true).userAgent(
					"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36")
					.header("x-client-data", RandomStringUtils.randomAlphanumeric(40));
			connection.proxy("127.0.0.1", 1080);
			Document doc = connection.timeout(12000).get();
			String dateTime = "0000-00-00";
			if (doc != null) {
				String body = StringUtils.substringAfter(doc.body().text(), "//");
				if (StringUtils.isNotEmpty(body)) {
					dateTime = Optional.ofNullable(UtilJson.convertValue(body, JsonNode.class))
							.filter(v -> v.isArray() && v.size() >= 1)
							.map(v -> StringUtils.stripToNull(v.get(0).at("/lt_dts").asText("")))
							.orElse("0000-00-01");
				}
			}
			back(miss.getId(), dateTime);
		} catch (HttpStatusException e) {
			System.out.println("url-err:{" + e.getStatusCode() + "}:------>" + url);
			back(miss.getId(), "0000-00-02");
		} catch (Exception e) {
			back(miss.getId(), "0000-00-03");
		}

	}



	private List<ZzYgTickerMiss> query(Integer lastId, Integer max) {
		return devJdbcTemplate.query(
				"select * from wl_search.wla_zz_yg_ticker_miss where ticker_id is null  and goog_upd like '0000%' and id > ?  and id <= ?  order by id asc limit 100",
				zzYgTickerMissRM,
				lastId, max);
	}



	private void back(Integer id, String remark) {
		devJdbcTemplate.update("update wl_search.wla_zz_yg_ticker_miss set goog_upd = ? where id = ?",
				remark, id);
	}



	private String genExchangeCode(String inputEx) {

		for (ExchangeGG gg : exchangeGGs) {
			if (StringUtils.equalsIgnoreCase(inputEx, gg.getGoogleCode()))
					return inputEx;
		}
		for (ExchangeGG gg : exchangeGGs) {
			if (StringUtils.equalsIgnoreCase(inputEx, gg.getAlias()) && StringUtils.isNotBlank(gg.getGoogleCode()))
				return gg.getGoogleCode();
		}
		return inputEx;
	}


	private List<ExchangeGG> getExchangeGG() {
		List<ExchangeGG> query2 = devJdbcTemplate.query("select * from wl_securities.wls_exchange where del = 0",
				exchangeRM);

		for (ExchangeGG gg : query2) {
			String str = devJdbcTemplate.queryForObject(
					"select max(exchange_code) from  wl_securities.wls_exchange_mapping where source_type = 3 and exchange_id = ? and del = 0",
					String.class, gg.getId());
			gg.setGoogleCode(str);
		}
		logger.info("exchangeGGs.size:{}", query2.size());
		return query2;
	}


	private final DataSource devDs = getDevDs();
	private final JdbcTemplate devJdbcTemplate = new JdbcTemplate(devDs);

	private final List<ExchangeGG> exchangeGGs = getExchangeGG();

	private static DataSource getDevDs() {
		try {
			ComboPooledDataSource ds0 = new ComboPooledDataSource();
			ds0.setJdbcUrl(
					"jdbc:mysql://192.168.40.203:3306?useUnicode=true&characterEncoding=utf8&useSSL=false&rewriteBatchedStatements=true&zeroDateTimeBehavior=convertToNull&useTimezone=true");
			ds0.setDriverClass("com.mysql.jdbc.Driver");
			ds0.setUser("dev");
			ds0.setMaxPoolSize(20);
			ds0.setPassword("dev");
			return ds0;
		} catch (Exception e) {
			return null;
		}
	}



	public static class ExchangeGG extends Exchange {

		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;
		/**
		 * 
		 */

		private String googleCode;

		public String getGoogleCode() {
			return googleCode;
		}

		public void setGoogleCode(String googleCode) {
			this.googleCode = googleCode;
		}

	}

	public static class ZzYgTickerMiss {

		private Integer id;
		private String symbol;
		private String exchangeCode;

		public Integer getId() {
			return id;
		}

		public void setId(Integer id) {
			this.id = id;
		}

		public String getSymbol() {
			return symbol;
		}

		public void setSymbol(String symbol) {
			this.symbol = symbol;
		}

		public String getExchangeCode() {
			return exchangeCode;
		}

		public void setExchangeCode(String exchangeCode) {
			this.exchangeCode = exchangeCode;
		}

	}
}
